/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年9月2日
 */
package com.massyframework.beanskin.launcher.scanning;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.util.version.Version;

/**
 * 基于Jar文件的资源扫描器
 * @author huangkh
 *
 */
class JarFileResourceScanner implements ModuleResourcesScanner<URL> {

	private static String PROTOCAL = "jar";
	private Logger logger = LoggerFactory.getLogger(JarFileResourceScanner.class);
	/**
	 * 
	 */
	public JarFileResourceScanner() {
		
	}

	@Override
	public void scanning(URL scope, Consumer<ModuleResources> action) {
		if (!scope.getProtocol().equals(PROTOCAL)) {
			return;
		}
		
		try {
			JarURLConnection conn = (JarURLConnection) scope.openConnection();
			JarFile jarFile = conn.getJarFile();
			
			Enumeration<JarEntry> em = jarFile.entries();
			int length = ModuleResourcesUtils.MODULE.length();
			
			Map<String, ModuleResources.Builder> builderMap =
					new HashMap<>();
			
			String prefix = null;
			while (em.hasMoreElements()) {
				JarEntry entry = em.nextElement();
				String name = entry.getName();
				
				if (entry.isDirectory()) {
					continue;
				}
				
				if (name.startsWith(ModuleResourcesUtils.MODULE)) {
					String path = name.substring(length);
				
	                if (path.length() == 0) continue;
	                String[] arr = path.split("/");
					if (arr.length > 3) {
						String groupId = arr[0];
						String moduleId = arr[1];
						String version = arr[2];
						try {
							Version.valueOf(version);
						}catch(Exception e) {
							if (logger.isErrorEnabled()) {
								logger.error(version.concat(" is not valid version format, skip scanning path:"
										.concat(jarFile.getName()).concat("!/").concat(name)));
							}
							continue;
						}
						
						prefix = groupId.concat("/").concat(moduleId).concat("/").concat(version);
						
						ModuleResources.Builder builder = builderMap.computeIfAbsent(prefix, key->
							ModuleResources.newBuilder()
								.groupId(groupId)
								.moduleId(moduleId)
								.version(version)
						);

						String uri = "jar:file:".concat(jarFile.getName()).concat("!/").concat(name);
		                builder.addResource(path, new URL(uri));
					}
				}
			}
		
			for (ModuleResources.Builder builder: builderMap.values()) {
				action.accept(builder.build());
			}
		}catch(IOException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getMessage(), e);
			}
		}
	}

	
}
